package com.ciwong.epaper.modules.wordlist.util;

import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;
import android.text.TextUtils;

import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.wordlist.bean.WordDownloadInfo;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.utils.StringUtils;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;

/**
 * Created by keepon on 2018/4/2.
 */

public class WordBookDownload {
    private static final String TAG = "WordBookDownload";
    public static final String URL_IS_NULL = "URL_IS_NULL";
    private BaseDownloadTask task;
    private static WordBookDownload instance;
    private WordDownloadInfo mCurrentPlayWordDownloadInfo;
    private WordOnPlayListener mOnPlayListener;

    private WordBookDownload() {

    }

    public static WordBookDownload getInstance() {
        if (instance == null) {
            instance = new WordBookDownload();
        }
        return instance;
    }

    public void startTask(WordDownloadInfo wordDownloadInfo) {//下载测试
        try {
            FileDownloader mFileDownloader = FileDownloader.getImpl();
            mFileDownloader.setMaxNetworkThreadCount(3);
            task = mFileDownloader.create(wordDownloadInfo.getAudioUrl())
                    .setPath(wordDownloadInfo.getLocalPath())
                    .setAutoRetryTimes(1)
                    .setTag(wordDownloadInfo)
                    .setForceReDownload(true)
                    .setListener(fileDownloadListener);
            task.start();
        } catch (Exception e) {
            e.getStackTrace();
        }

    }


    FileDownloadListener fileDownloadListener = new FileDownloadListener() {

        @Override
        protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

        }


        @Override
        protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {

        }

        @Override
        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
        }

        @Override
        protected void completed(BaseDownloadTask task) {
            WordDownloadInfo wordDownloadInfo = (WordDownloadInfo) task.getTag();
            if (wordDownloadInfo != null && mCurrentPlayWordDownloadInfo != null && wordDownloadInfo.getWord().equals(mCurrentPlayWordDownloadInfo.getWord())) {
                if (mOnPlayListener != null) {
                    mOnPlayListener.onDownloadCompelted(wordDownloadInfo);
                    File localAudioPath = getLocalAudioPath(wordDownloadInfo);
                    if (localAudioPath.exists()) {
                        if (AudioPlayer.getInstance().isPlaying()) {
                            AudioPlayer.getInstance().stop();
                        }
                        AudioPlayer.getInstance().setOnPlayListener(mOnPlayListener).play(BaseConstants.FILE_PREFIX + localAudioPath.getAbsolutePath(),
                                true);
                        try {
                            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && EApplication.getInstance().mPlayerspeed != 1.0f) {
                                MediaPlayer mMediaPlayer = AudioPlayer.getInstance().getMediaPlayer();
                                if (mMediaPlayer != null) {
                                    try {
                                        PlaybackParams params = mMediaPlayer.getPlaybackParams().setSpeed(EApplication.getInstance().mPlayerspeed);
                                        if (params != null) {
                                            mMediaPlayer.setPlaybackParams(params);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

        @Override
        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
        }

        @Override
        protected void error(BaseDownloadTask task, Throwable e) {
            WordDownloadInfo wordDownloadInfo = (WordDownloadInfo) task.getTag();
            if (wordDownloadInfo != null && mCurrentPlayWordDownloadInfo != null && wordDownloadInfo.getWord().equals(mCurrentPlayWordDownloadInfo.getWord())) {
                if (mOnPlayListener != null) {
                    mOnPlayListener.onDownloadFailed(wordDownloadInfo, e);
                }
            }
        }

        @Override
        protected void warn(BaseDownloadTask task) {

        }
    };


    /**
     * @param wordDownloadInfo 需通过isNativeAudio字段设置是原生音频是录音音频，存放于不同的文件夹
     * @param OnPlayListener
     */
    public void startPlay(WordDownloadInfo wordDownloadInfo, WordOnPlayListener OnPlayListener) {
        mCurrentPlayWordDownloadInfo = wordDownloadInfo;
        mOnPlayListener = OnPlayListener;
        if (TextUtils.isEmpty(wordDownloadInfo.getAudioUrl())) {
            OnPlayListener.onDownloadFailed(wordDownloadInfo, new Throwable(URL_IS_NULL));
            return;
        }
        File localAudioPath = getLocalAudioPath(wordDownloadInfo);
        if (localAudioPath.exists()) {
            if (AudioPlayer.getInstance().isPlaying()) {
                AudioPlayer.getInstance().stop();
            }
            AudioPlayer.getInstance().setOnPlayListener(OnPlayListener).play(BaseConstants.FILE_PREFIX + localAudioPath.getAbsolutePath(),
                    true);
            try {
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && EApplication.getInstance().mPlayerspeed != 1.0f) {
                    MediaPlayer mMediaPlayer = AudioPlayer.getInstance().getMediaPlayer();
                    if (mMediaPlayer != null) {
                        try {
                            PlaybackParams params = mMediaPlayer.getPlaybackParams().setSpeed(EApplication.getInstance().mPlayerspeed);
                            if (params != null) {
                                mMediaPlayer.setPlaybackParams(params);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            OnPlayListener.onDownloading(wordDownloadInfo);
            wordDownloadInfo.setLocalPath(localAudioPath.getPath());
            startTask(wordDownloadInfo);
        }


    }

    public File getLocalAudioPath(WordDownloadInfo wordDownloadInfo) {
        if (wordDownloadInfo.isNativeAudio()) {
            return new File(ESystem.getWordListNativePath(),
                    StringUtils.md5(wordDownloadInfo.getWord())
                            + EConstants.AUDIO_DEFAULT_SUFFIX);

        } else {
            return new File(ESystem.getWordListRecordPath(),
                    StringUtils.md5("record" + wordDownloadInfo.getWord()) + EConstants.AUDIO_DEFAULT_SUFFIX);
        }

    }
}
